package ua.mk.chdu.rtem.diploma.core.agents.scheduling.behaviours;

import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import ua.mk.chdu.rtem.diploma.core.agents.scheduling.TaskSchedulingAgent;
import ua.mk.chdu.rtem.diploma.core.model.enums.MessageTypes;
import ua.mk.chdu.rtem.diploma.core.model.vo.TaskCompletionVO;
import ua.mk.chdu.rtem.diploma.core.utils.MessageContentExtractor;

import java.util.ArrayList;
import java.util.List;

public class ProcessTaskCompletionBehaviour extends SimpleBehaviour {
    private TaskSchedulingAgent agent;
    private List<String> resultList = new ArrayList<String>();
    private MessageTemplate template = MessageTemplate.MatchInReplyTo(MessageTypes.PROCESS_TASK_PART.getValue());
    private MessageContentExtractor<TaskCompletionVO> extractor = new MessageContentExtractor<TaskCompletionVO>();

    public ProcessTaskCompletionBehaviour(TaskSchedulingAgent agent) {
        this.agent = agent;
    }


    @Override
    public void action() {
        //We need to block action performing until message not received.
        block();
        ACLMessage taskCompletedMessage = agent.receive(template);
        TaskCompletionVO messageVO = extractor.extract(taskCompletedMessage);
        resultList.add(messageVO.getValueObject());
    }

    @Override
    public boolean done() {
        if (resultList.size() == agent.getModel().getTaskCount()) {
            agent.getModel().setResultList(resultList);
            return true;
        }
        return false;
    }
}
